class Watermark {
    constructor(options = {}) {
        // 默认配置
        const defaultOptions = {
            width: 150,         // 水印宽度
            height: 100,        // 水印高度
            rotate: -30,        // 旋转角度
            fontSize: 13,       // 字体大小
            fontFamily: 'Arial',// 字体类型
            opacity: 0.09,      // 透明度
            staticText: '',     // 静态文本内容
            showTime: false,    // 是否显示时间
            timeOffset: 0,      // 时间文本的垂直偏移
            zIndex: 99999,      // 水印层级
            timeFormat: {       // 时间格式化选项
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            },
            updateInterval: 1000, // 时间更新间隔（毫秒）
            preventTamper: true,  // 是否防止篡改
            container: document.body // 水印容器
        };

        this.options = { ...defaultOptions, ...options };
        this.init();
    }

    init() {
        const watermarkDiv = document.createElement('div');
        watermarkDiv.id = 'watermark-container';
        watermarkDiv.style.cssText = `
            position: fixed;
            top: -20px;
            left: -20px;
            width: calc(100% + 40px);
            height: calc(100% + 40px);
            pointer-events: none;
            z-index: 99999;
        `;

        const canvasContainer = document.createElement('div');
        canvasContainer.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-repeat: repeat !important;
            background-position: -10px -10px !important;
            background-size: ${this.options.width}px ${this.options.height}px !important;
        `;

        // 创建静态内容的canvas
        const staticCanvas = this.createCanvas([this.options.staticText], 0);
        this.staticCanvas = staticCanvas;
        
        if (this.options.showTime) {
            // 只有在需要显示时间时才创建时间canvas
            const timeCanvas = this.createCanvas([''], this.options.fontSize);
            this.timeCanvas = timeCanvas;

            canvasContainer.style.background = `
                url(${staticCanvas.toDataURL()}) repeat,
                url(${timeCanvas.toDataURL()}) repeat
            `;
            
            // 开始更新时间
            this.startTimeUpdate();
        } else {
            // 只显示静态内容
            canvasContainer.style.background = `url(${staticCanvas.toDataURL()}) repeat`;
        }

        watermarkDiv.appendChild(canvasContainer);
        document.body.appendChild(watermarkDiv);

        // 防止水印被删除
        this.observeWatermark(watermarkDiv);
    }

    createCanvas(lines, yOffset = 0) {
        const canvas = document.createElement('canvas');
        canvas.width = this.options.width;
        canvas.height = this.options.height;
        
        const ctx = canvas.getContext('2d');
        
        // 重置变换矩阵
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        
        ctx.font = `${this.options.fontSize}px Arial`;
        ctx.fillStyle = `rgba(0, 0, 0, ${this.options.opacity})`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        ctx.translate(this.options.width / 2, this.options.height / 2 + yOffset);
        ctx.rotate((this.options.rotate * Math.PI) / 180);
        
        const lineHeight = this.options.fontSize + 1; // 进一步减小行间距
        const startY = -(lines.length - 1) * lineHeight / 2;
        
        lines.forEach((line, index) => {
            ctx.fillText(line, 0, startY + index * lineHeight);
        });

        return canvas;
    }

    updateTime(timeStr) {
        if (!this.options.showTime || !this.timeCanvas) return;
        
        const ctx = this.timeCanvas.getContext('2d');
        
        ctx.save();
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.clearRect(0, 0, this.options.width, this.options.height);
        ctx.restore();
        
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.font = `${this.options.fontSize}px Arial`;
        ctx.fillStyle = `rgba(0, 0, 0, ${this.options.opacity})`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        ctx.translate(this.options.width / 2, this.options.height / 2 + this.options.fontSize);
        ctx.rotate((this.options.rotate * Math.PI) / 180);
        
        ctx.fillText(timeStr, 0, 0);

        const container = document.querySelector('#watermark-container div');
        if (container) {
            container.style.background = `
                url(${this.staticCanvas.toDataURL()}) repeat,
                url(${this.timeCanvas.toDataURL()}) repeat
            `;
        }
    }

    startTimeUpdate() {
        const updateWithTime = () => {
            const now = new Date();
            const timeStr = now.toLocaleString('zh-CN', this.options.timeFormat);
            this.updateTime(timeStr);
        };

        updateWithTime();
        this.timer = setInterval(updateWithTime, this.options.updateInterval);
    }

    observeWatermark(watermarkDiv) {
        const observer = new MutationObserver(() => {
            if (!document.getElementById('watermark-container')) {
                document.body.appendChild(watermarkDiv);
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // 提供销毁方法
    destroy() {
        if (this.timer) {
            clearInterval(this.timer);
        }
        const watermarkDiv = document.getElementById('watermark-container');
        if (watermarkDiv) {
            watermarkDiv.remove();
        }
    }

    // 提供更新配置的方法
    updateOptions(newOptions) {
        this.destroy();
        this.options = { ...this.options, ...newOptions };
        this.init();
    }
} 